//
//  ByNetWechatPayApi.m
//  beibei_ios
//
//  Created by pro on 16/5/23.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByNetWechatPayApi.h"

@implementation ByNetWechatPayApi

/** 微信预支付接口 直接做了向微信请求的操作 */
+ (void)wechatForePayRequest:(ByNetWechatPayModel *)model
                     failure:(void(^)(ByNetBaseResult *result))failure {
    
    static NSString *apiType = @"By_Wxpay_prePay";
    static NSInteger apiVersion = 100;
    int rand = arc4random() % 1000;
    
    NSString *requestId = [NSString stringWithFormat:@"%ld%d", (NSInteger)[NSDate currentDateTimeInterval], rand];
    
    // 拼接参数
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:model.code forKey:@"order_code"];
    if (model.total_price) {
        [params setObject:model.total_price forKey:@"total_price"];
    }
    if (model.desc) {
        [params setObject:model.desc forKey:@"desc"];
    }
    
   
    // 返回的responseObject 可能是字符串也可能是字典
    [self post:requestId
       apiType:apiType
      dataType:ByNetDataTypeDictionary
     apiVerson:apiVersion
        params:params
       success:^(NSURLSessionDataTask *operation, id responseObject, NSString *notify_id) {
           [ByCoreToolAlert hideHud];
           NSLog(@"******** 微信预支付 -> 成功: %@", responseObject);
           PayReq *request = [[PayReq alloc] init];
           request.partnerId = responseObject[@"partnerid"];
           request.prepayId= responseObject[@"prepayid"];
           request.package = responseObject[@"package"];
           request.nonceStr= responseObject[@"noncestr"];
           request.timeStamp = [responseObject[@"timestamp"] intValue];
           request.sign = responseObject[@"sign"];
           
           BOOL success = [WXApi sendReq:request];
           if (success) {
//               if(failure) {
//                   ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
//                   result.code = -1;
//                   result.msg = @"预支付请求失败";
//                   result.data = @"预支付请求失败";
//                   failure(result);
//               } else {
//                   [ByCoreToolAlert showFailureWithText:@"预支付请求失败"];
//               }
           }
    
       } failure:^(NSURLSessionDataTask *operation, NSError *error){
           
           [ByCoreToolAlert hideHud];
           NSLog(@"******** 张占彬 微信预支付 -> 失败: %@", error);
           
           ByNetBaseResult *result = [[ByNetBaseResult alloc] init];
           result.code = error.code;
           result.msg = error.domain;
           result.data = error.localizedDescription;
           if(failure) {
               failure(result);
           } else {
               [ByCoreToolAlert showFailureWithText:result.msg];
           }
       }];
}
@end
